<?php
namespace app\sub\controller;

use PHPQRCode\QRcode;
use think\Db;
use think\facade\Config;

class Lot extends \Common {

    private $spec = ["size" => "规格"];

    # 获取自己名下的专场
    public function GetLots(){
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        if(isset($_GET["limit"]) && isset($_GET["page"]) && isset($_GET["name"])){
            $name = $_GET["name"];
            $limit = $_GET["limit"];
            $page = $_GET["page"];
            if($name != ""){
                $lots = Db::name("lot")
                    ->where("aid", $aid)
                    ->where("is_del", 0)
                    ->where("name like '%{$name}%'")
                    ->order("state desc,lid desc")
                    ->page($page, $limit)
                    ->select();
                $count = Db::name("lot")
                    ->where("aid", $aid)
                    ->where("is_del", 0)
                    ->where("name like '%{$name}%'")
                    ->count();
            }else{
                $lots = Db::name("lot")
                    ->where("aid", $aid)
                    ->where("is_del", 0)
                    ->order("state desc,lid desc")
                    ->page($page, $limit)
                    ->select();
                $count = Db::name("lot")
                    ->where("aid", $aid)
                    ->where("is_del", 0)
                    ->count();
            }

            $data = [];
            if(!empty($lots)){
                foreach ($lots as $val){
                    $GoodCount = Db::name("goods")->where("lid", $val["lid"])->count();
                    # 封面图片
                    $coverUrl = "";
                    if($val["logo"] != ""){
                        if(is_file("./static/upload/cover/{$val["logo"]}")){
                            $coverUrl = Config::get("app.ip")."static/upload/cover/{$val["logo"]}?t=".time();
                        }
                    }

                    $data[] = [
                        "cover" => $coverUrl,
                        "id" => (int)$val["lid"],
                        "name" => $val["name"],
                        "num" => (int)$GoodCount,
                        "time" => [$val["start_time"]*1000, $val["end_time"]*1000],
                        "show" => $val["is_over"] == 0,
                        "remark" => $val["remark"],
                        "rate" => $val["rate"]
                    ];
                }
            }

            $h5Url = Config::get("app.ip")."mobile/#/?subid={$aid}";
            QRcode::png($h5Url, "./static/upload/mobileQr/{$aid}.jpg", "L", 6, 1);
            $h5qr = Config::get("app.ip")."static/upload/mobileQr/{$aid}.jpg?t=".time();

            $array = [
                "list" => $data,
                "total" => $count,
                "mobile_qr" => $h5qr
            ];

            Code(200, false, $array);
        }else{
            Code(403, "服务器错误，请稍后再试");
        }

    }

    # 编辑或添加专场 [Qt: 添加汇率字段]
    public function SetLot(){
        $aid = $this->token["id"];
        if(isset($_POST["name"]) && isset($_POST["time"]) && isset($_POST["remark"]) && isset($_POST["show"])){
            $name = $_POST["name"];
            $time = $_POST["time"];
            $rate = (isset($_POST["rate"]) && $_POST["rate"] != "") ? $_POST["rate"] : 1;
            $timeRrange = explode(",", $time);
            $start = $timeRrange[0] / 1000;
            $end = $timeRrange[1] / 1000;
            $remark = $_POST["remark"];
            $show = $_POST["show"] == "true" ? 0 : 1;
            $view = rand(1000, 9999);
            $coverId = null;

            $info = [
                "aid" => $aid,
                "name" => $name,
                "start_time" => $start,
                "end_time" => $end,
                "remark" => $remark,
                "is_over" => $show,
                "rate" => $rate
            ];
            if(isset($_POST["id"])){
                $msg = "专场信息修改成功";
                $lid = $_POST["id"];
                $lot = Db::name("lot")->where("lid != $lid")->where("name", $name)->find();
                if(empty($lot)){
                    Db::name("lot")->where("lid", $lid)->update($info);
                    $coverId = $lid;
                }else{
                    Code(403, "专场名称已存在");
                }
            }else{
                $msg = "专场信息添加成功";
                $info["view"] = $view;
                $lot = Db::name("lot")->where("name", $name)->find();
                if(empty($lot)){
                    $coverId = Db::name("lot")->insertGetId($info);
                }else{
                    Code(403, "专场名称已存在");
                }
            }

            # 封面图片
            $coverUrl = "";
            if(isset($_FILES["cover"])){
                $coverImage = UploadFile($_FILES["cover"], $coverId, "./static/upload/cover/");
                if($coverImage){
                    $up = [
                        "logo" => $coverImage
                    ];
                    Db::name("lot")->where("lid", $coverId)->update($up);
                }
                $coverUrl = Config::get("app.ip")."static/upload/cover/{$coverId}.jpg?t=".time();
            }

            # 专场下多少拍品
            $num = Db::name("goods")->where("lid", $coverId)->count();

            $array = [
                "id" => (int)$coverId,
                "cover" => $coverUrl,
                "name" => $name,
                "num" => (int)$num,
                "remark" => $remark,
                "show" => $_POST["show"] == true,
                "time" => $timeRrange,
                "rate" => $rate
            ];
            Code(200, $msg, $array);
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 删除专场
    public function DelLot(){
        if(isset($_POST["id"])){
            $update = [
                "is_del" => 1
            ];
            Db::name("lot")->where("lid", $_POST["id"])->update($update);
            Code(200, "删除成功", (Object)[]);
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 设置专场的状态 [Qt: 结束的时候查看是否有正在拍卖的拍品]
    public function SetLotState(){
        if(isset($_POST["id"]) && isset($_POST["state"])){
            $lid = $_POST["id"];
            $state = $_POST["state"];

            $upInfo = [
                "state" => $state
            ];
            if($state == 2){
                $upInfo["correct_end_time"] = $this->TransformTime(time(), '23', '59', '59');
            }else{
                $upInfo["correct_start_time"] = $this->TransformTime(time(), '0', '0', '0');
            }
            Db::name("lot")->where("lid", $lid)->update($upInfo);
            // 是否需要查看当前是否有正在拍卖的拍品，进行流拍
            if($state == 2){
                $send = [
                    "type" => "end",
                    "lot_id" => $lid
                ];
                $this->sendTogrounp($send, $lid);
            }
            $array = [
                "id" => (int)$lid,
                "state" => (int)$state
            ];
            Code(200, false, $array);
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 获取专场详细信息
    public function GetLotData(){
        $aid = $this->token["id"];
        if(isset($_GET["id"])){
            $lid = $_GET["id"];

            $lot = Db::name('lot')
                ->where("is_over", 0)
                ->where("is_del", 0)
                ->where("lid", $lid)
                ->where("aid", $aid)
                ->find();

            if(!empty($lot)){
                # 获取全部商品列表
                $Goods = Db::name('goods')
                    ->where("lid", $lid)
                    ->order("number asc")
                    ->select();

                # 未开拍总数
                $NoStartNum = Db::name('goods')
                    ->where("lid", $lid)
                    ->where("state", 0)
                    ->count();

                # 获拍总数
                $GetGoodNum = Db::name('goods')
                    ->where("lid", $lid)
                    ->where(function ($query){
                        $query->where("state", 3)->whereOr("state", 4)->whereOr("state", 5);
                    })
                    ->count();

                # 流拍总数
                $PassByNum = Db::name('goods')
                    ->where("lid", $lid)
                    ->where("state", 6)
                    ->count();

                #所有拍品总数
                $AllGood = Db::name('goods')
                    ->where("lid", $lid)
                    ->count();

                # 成交价格总数
                $DealAllPrice = Db::name('goods')
                    ->where("lid", $lid)
                    ->where(function ($query){
                        $query->where("state", 3)->whereOr("state", 4)->whereOr("state", 5);
                    })
                    ->field("SUM(final_price) as all_price")
                    ->find();

                # 近期交易前三条
                $RecentLimit = Db::name('goods')
                    ->where("lid", $_GET["id"])
                    ->where(function ($query){
                        $query->where("state", 3)->whereOr("state", 4)->whereOr("state", 5)->whereOr("state", 6);
                    })
                    ->order("clinch_time desc")
                    ->limit(3)
                    ->select();

                $good = []; $index = null; $bids = []; $no_index = null; $disRevoke = true;
                if(!empty($Goods)){
                    foreach ($Goods as $key => $value){
                        $image = $this->SearchImg($value["lid"], $value["number"]);
                        if($value["state"] == 1){
                            $index = $key;

                            $number = $this->GetPeople($value);
                            if($value["final_price"] != 0){
                                $bids[] = [
                                    "num" => (is_bool($number) && !$number) ? 0 : $number,
                                    "bid" => $value["final_price"]
                                ];
                            }

                            if($value["revoke_bid"] != ""){
                                $revoke = json_decode($value["revoke_bid"], true);
                                $revoke_num = $this->GetPeople($revoke);
                                $bids[] = [
                                    "num" => (is_bool($revoke_num) && !$revoke_num) ? 0 : $revoke_num,
                                    "bid" => $revoke["final_price"]
                                ];
                                $disRevoke = false;
                            }
                        }

                        if($no_index === null && $value["state"] == 0){
                            $no_index = $key;
                        }

                        $number = $this->GetPeople($value);

                        $good[] = [
                            "id" => (int)$value["gid"],
                            "cover" => $image[0],
                            "curr" => $value["final_price"] == 0 ? $value["price"] : $value["final_price"],
                            "curr_buyer" => $value["final_price"] == 0 ? "" : ((is_bool($number) && !$number) ? 0 : $number),
                            "final" => $this->GetFinal($value),
                            "lot" => $value["number"],
                            "name" => $value["name"],
                            "start" => $value["price"],
                            "state" => ($value["state"] == 0 || $value["state"] == 1) ? (int)$value["state"] : 2,
                            "spec" => $this->Spec($value, $this->spec)
                        ];
                    }

                    if($index === null && $no_index != ""){
                        $index = $no_index;
                    }

                    $recent = [];
                    if(!empty($RecentLimit)){
                        foreach ($RecentLimit as $value){
                            $num = $this->GetPeople($value);

                            $recent[] = [
                                "buyer_num" => $value["final_price"] == 0 ? "" : (is_bool($num) && !$num) ? $value["peo_num"] : $num,
                                "buyer_way" => $value["final_price"] == 0 ? "" : (is_bool($num) && !$num) == 0 ? "现场" : "网络",
                                "final" => $this->GetFinal($value),
                                "lot" => $value["number"],
                            ];
                        }
                    }


                    $LiveUrl = "";
                    $LiveQr = "";
                    if($lot["is_turnon"] == 1){
                        $LiveUrl = $this->getPushUrl("lot".$lot["lid"], date("Y-m-d H:i:s", time() + 3600*72));
                        QRcode::png($LiveUrl, "./static/upload/liveQr/".$lot["lid"].".jpg", "L", 6, 1);
                        $LiveQr = Config::get("app.ip")."static/upload/liveQr/".$lot["lid"].".jpg?t=".time();
                    }

                    $h5Url = Config::get("app.ip")."mobile/#/?subid={$aid}";
                    QRcode::png($h5Url, "./static/upload/mobileQr/{$aid}.jpg", "L", 6, 1);
                    $h5qr = Config::get("app.ip")."static/upload/mobileQr/{$aid}.jpg?t=".time();

                    $array = [
                        "deal" => [$DealAllPrice["all_price"] == null ? "0" : $DealAllPrice["all_price"], round($GetGoodNum/$AllGood*100,2)."%"],
                        "goods" => $good,
                        "id" => (int)$lot["lid"],
                        "index" => (int)$index,
                        "name" => $lot["name"],
                        "num" => [$AllGood, $GetGoodNum, $PassByNum, $NoStartNum],
                        "recent" => $recent,
                        "state" => (int)$lot["state"],
                        "livePush" => [
                            "play" => $lot["is_turnon"] == 1,
                            "qr" => $LiveQr,
                            "url" => $LiveUrl
                        ],
                        "bids" => $bids,
                        "disRevoke" => $disRevoke,
                        "h5qr" => $h5qr
                    ];

                    Code(200, false, $array);
                }else{
                    Code(403, "专场内无拍品");
                }
            }else{
                Code(403, "专场不存在");
            }
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 获取正在进行的拍卖专场
    public function GetAucingLots(){
        $aid = $this->token["id"];
        $lot = Db::name("lot")->where("aid", $aid)->where("state", 1)->select();
        $array = [];
        if(!empty($lot)){
            foreach ($lot as $value){
                $array[] = [
                    "id" => (int)$value["lid"],
                    "name" => $value["name"]
                ];
            }
        }

        Code(200, false, $array);
    }

    # 获取全部专场
    public function GetAllLots(){
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        $data = [];
        $lot = Db::name("lot")->where("is_del", 0)->where("aid", $aid)->select();
        if(!empty($lot)){
            foreach ($lot as $value){
                $data[] = [
                    "id" => (int)$value["lid"],
                    "name" => $value["name"]
                ];
            }
        }

        Code(200, false, $data);
    }

    # 清空专场下的拍品
    public function EmptyLot()
    {
        if(isset($_POST["id"])){
            Db::name("goods")->where("lid", $_POST["id"])->delete();
            Code(200, "清空成功");
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

}
